package whu.cachhe.makeorder.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

/**
 * Only supports ONE drawable at left, top, right, or bottom. The second one will be simply ignored.
 *
 * Created by CocoAdapter on 2018/2/10.
 */

public class ImageTextView extends android.support.v7.widget.AppCompatTextView {
    public ImageTextView(Context context) {
        super(context);
    }

    public ImageTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas = getTopCanvas(canvas);
        super.onDraw(canvas);
    }

    @SuppressWarnings("all")
    private Canvas getTopCanvas(Canvas canvas) {
        Drawable[] drawables = getCompoundDrawables();
        if (drawables == null)
            return canvas;

        Drawable drawable = null;
        int directionFlag = -1;
        for (int i = 0; i < 4; i++){
            if (drawables[i] != null){
                drawable = drawables[i];
                directionFlag = i;
                break;
            }
        }

        if (directionFlag == 0 || directionFlag == 2){ // left or right
            float textWidth = getPaint().measureText(getText().toString());
            int drawWidth = drawable.getIntrinsicWidth();
            int drawPadding = getCompoundDrawablePadding();
            float contentWidth = textWidth + drawWidth + drawPadding;

            float dx = (getWidth() - contentWidth) / 2;
            if (directionFlag == 2)
                dx = -dx;
            canvas.translate(dx, 0);
        } else if (directionFlag == 1 || directionFlag == 3) { // top or bottom
            Rect rect = new Rect();
            getPaint().getTextBounds(getText().toString(), 0, getText().toString().length(), rect);
            float textHeight = rect.height();
            int drawHeight = drawable.getIntrinsicHeight();
            int drawPadding = getCompoundDrawablePadding();
            float contentHeight = textHeight + drawHeight + drawPadding;

            float dy = (getHeight() - contentHeight) / 2;
            if (directionFlag == 3)
                dy = -dy;

            canvas.translate(0, dy);
        }

        return canvas;
    }
}
